<?php

namespace app\product\logic;
use app\common\service\UploadService;
use app\data\util\MqQueueName;
use app\order\logic\OrderBtLogic;
use app\product\logic\BasicLogic;
use app\api\logic\FeiShuMessageLogic;
use app\order\logic\OrderLogic;
use app\purchase\logic\PlanSuggestLogic;
use app\systems\logic\MqTaskPushLogic;
use think\facade\Db;
use app\common\library\Excel;

class ContractLogic extends BasicLogic
{

    /**
     * @desc   获取批次号列表
     * @author luckyXiong
     * @date   2024-10-29
     */
    public function getList($params=[]){
        $spu             = $params['spu']??'';
        $batch_id        = $params['batch_id']??'';
        $operate_id      = $params['operater_id']??'';
        $supply_id       = getIsset($params,'supply_id');
        $confirm_status  = getIsset($params,'confirm_status');
        $check_time      = getIsset($params,'check_time');
        $create_time     = getIsset($params,'create_time');
        $limit           = getIsset($params,'limit',10);
        $where           = [];

        if($spu){
            $where[] = ['spu', '=', $spu];
        }

        if($confirm_status){
            $where[] = ['confirm_status', '=', $confirm_status];
        }

        if($batch_id){
            $where[] = ['batch_id', '=', $batch_id];
        }

        if($operate_id){
            $where[] = ['operate_id', '=', $operate_id];
        }

        if (!empty($check_time)) {
            $where[]  = ['check_time', '>=', date('Y-m-d H:i:s',strtotime($check_time[0]))];
            $where[]  = ['check_time', '<=', date('Y-m-d H:i:s',strtotime($check_time[1]) + 3600*24-1)];
        }

        if (!empty($create_time)) {
            $where[]  = ['create_time', '>=', date('Y-m-d H:i:s',strtotime($create_time[0]))];
            $where[]  = ['create_time', '<=', date('Y-m-d H:i:s',strtotime($create_time[1]) + 3600*24-1)];
        }


        if($supply_id){
            $where[] = ['supply_id', '=',$supply_id];
        }


        $field = '*';
        $res   = Db::name('product_contract')
            ->field($field)
            ->where($where)
            ->order('create_time desc')
            ->paginate($limit);
        $list = $res->items()?:[];

        $data = [
            'list'   => $list,
            'total'  => $res->total(),
        ];
        return  $this->jsonMessage(200,true,'获取成功',$data);
    }



    /**
    * @desc    详情
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function info($params=[])
    {
        $id = $params['id'] ?? 0;
        $product_contract = Db::name('product_contract')->where('id',$id)->find();
        if (empty($product_contract)) {
            return json(DefaultResponse(201, false, '数据不存在!', null));
        }
        return json(DefaultResponse(200, true, '获取成功', $product_contract));
    }


    /**
     * @desc   合同详情
     * @author zhangheng
     * @date   2025-06-18
     */
    public  function contact_info($params=[]){
        //合同批次号;
        $batch_id = $params['batch_id']??'';

        if (empty($batch_id)){
            return  $this->jsonMessage(201,false,'合同批次号不能为空!','');
        }

        $field = 'spu,seller_sku,product_type,single_price,supply_name,suggest_sku_nums,color,cup,size';
        $list  = Db::name('purchase_suggest_water')->field($field)->where(['batch_id'=>$batch_id])->select()->toArray();
        $current_info = current($list);

        //批量获取seller_sku
        $seller_skus= array_column($list,'seller_sku');
        $map   = [];
        $map[] = ['spu','=',$current_info['spu']];
        $map[] = ['seller_sku','not in',$seller_skus];
        //未出现在要补货的spu里面的sku尺码获取
        $field = 'id,spu,seller_sku,color,size,cup';
        $other_size = Db::name('order_sku_size')->field($field)->where($map)->select()->toArray();
        $arr_size = [];
        if($other_size){
            foreach($other_size as $k=>$v){
                $arr_size[$k]['spu']              = $v['spu'];
                $arr_size[$k]['seller_sku']       = $v['seller_sku'];
                $arr_size[$k]['product_type']     = $current_info['product_type'];
                $arr_size[$k]['supply_name']      = $current_info['supply_name'];
                $arr_size[$k]['suggest_sku_nums'] = "";
                $arr_size[$k]['color']            = $v['color'];
                $arr_size[$k]['size']             = $v['size'];
                $arr_size[$k]['cup']              = $v['cup'];
            }
        }

        $cup = $current_info['cup']??"";

        //非罩杯的加尺码
        if($arr_size && empty($cup)){
            $list = array_merge($list,$arr_size);
        }


        if($cup){
            $list =(new PlanSuggestLogic())->sort_cup($list);
        }else{
            $list =(new PlanSuggestLogic())->sort_size($list);
        }

        //批量获取产品名称;
        $spus              = array_column($list,'spu');
        $spus              = array_values(array_unique($spus));
        $product_names     = Db::name('product')->field('id,spu,product_name')->whereIn('spu',$spus)->select()->toArray();
        $product_names_map = array_column($product_names,'product_name','spu');
        $current           = current($list);
        if(!isset($current['spu']))  return  $this->jsonMessage(201,false,'暂未生成合同数据!',null);
        foreach($list as $k=>$v){
            $list[$k]['product_name']      = $product_names_map[$v['spu']]??'';
            $list[$k]['arraive_time']      = '';
            $list[$k]['remark']            = '';
        }
        return  $this->jsonMessage(200,true,'获取成功',$list);
    }


    /**
     * @desc   确认下单操作
     * @author zhangheng
     * @date   2025-06-18
     */
    public function confirm_order($params=[]){
        //合同批次号;
        $batch_id = $params['batch_id']??'';
        $sku_list = $params['sku_list']??'';
        htmlLog(['sku_list'=>$sku_list],OPERATE_LOG . date('Ym') . '/confirm_order/' . date('Ymd') . '.txt');
        foreach($sku_list as $v){
            if(empty($v['suggest_sku_nums'])){
                 continue;
            }
            // 队列处理
            MqTaskPushLogic::mq_task_push(
                '',
                MqQueueName::QUEUE_ORDER_CONTACT_QUEUE,
                [
                    'batch_id'         =>$batch_id,
                    'seller_sku'       =>$v['seller_sku'],
                    'suggest_sku_nums' =>$v['suggest_sku_nums'],
                    'single_price'     =>$v['single_price']??'',
                ],
                false
            );
        }
        //更新合同批次状态;
        Db::name('product_contract')->where(['batch_id'=>$batch_id])->update(
            [
                'confirm_status'=>2,
                'check_time'    =>date("Y-m-d H:i:s",time()),
            ]
        );
        //直接触发MQ消费 2024-11-30
        (new OrderBtLogic())->getCrontab();
        return  $this->jsonMessage(200,true,'操作成功','');
    }






    /**
     * @desc   备货建议seller_sku列表接口
     * @author luckyXiong
     * @date   2025-06-18
     */
    private function get_size($seller_sku,$product_type){
        //获取spu
        $spu_info    = explode('-', $seller_sku);
        $spu         = $spu_info[0];
        $letter_arr  = ['A','B','C','D','E','F','G','H','I','J','K','L','M'];
        $cup         = '';
        $size        = '';
        $color       = $spu_info[1]??'';

        if($product_type==1){
            //bra类型 拆分尺寸和罩杯;
            preg_match_all('/[0-9]+|[a-zA-Z]+/', $spu_info[2], $matches);
            $letter = $matches[0][1]??'';
            if(in_array($letter,$letter_arr)){
                $size = $matches[0][0]??'';
                $cup  = $letter;
            }else{
                $size = $spu_info[2];
                $cup  = '';
            }
        }else{
            $size = $spu_info[2];
        }
        return  [
            'color'=>$color,
            'size' =>$size,
            'cup'  =>$cup,
        ];

    }

    


    /**
     * @desc   获取批次号列表
     * @author luckyXiong
     * @date   2024-10-28
     */
    public function add_contract($params=[]){
        $admin_id     = $params['admin_id']??'';
        $batch_id     = self::get_batch_id($admin_id);
        $create_operator = Db::name('system_admin')->where(['id'=>$admin_id])->value('username');
        $exist_info = Db::name('product_contract')->where(['batch_id'=>$batch_id])->find();
        if($exist_info){
            $batch_id = self::get_batch_id($admin_id);
        }
        Db::name('product_contract')->insert(
            [
                'batch_id'       =>$batch_id,
                'create_time'    =>date("Y-m-d H:i:s",time()),
                'create_operator'=>$create_operator,
            ]
        );

        //update 2024-10-29 飞书消息
        $open_id = Db::name('system_admin')->where('id',$admin_id)->value('open_id');
        $msg     = "您生成的合同批次号为: ".$batch_id;
        if($open_id){
            $msg_info = [
                'message' => $msg,
                'open_id' => $open_id,
            ];
            (new FeiShuMessageLogic())->send_message($msg_info);
        }
        return     $this->jsonMessage(200,true,'获取成功',$batch_id);
    }


    /**
     * @desc   编辑批次号列表
     * @author luckyXiong
     * @date   2024-10-29
     */
    public function edit_contract($params=[]){
         $id           = $params['id']??'';
         $admin_id     = $params['admin_id']??'';
         $batch_id     = $params['batch_id']??'';
         $purchase_number  = $params['purchase_number']??'';
         $create_operator = Db::name('system_admin')->where(['id'=>$admin_id])->value('username');
         if(!$id) return  $this->jsonMessage(201,false,'ID不能为空!',null);
         Db::name('product_contract')->where(['id'=>$id])->update(
             [
                 'batch_id'         =>$batch_id,
                 'purchase_number'  =>$purchase_number,
                 'create_time'      =>date("Y-m-d H:i:s",time()),
                 'create_operator'  =>$create_operator,
             ]
         );
        return     $this->jsonMessage(200,true,'操作成功',$batch_id);
    }



    /**
     * @desc   删除批次号列表
     * @author luckyXiong
     * @date   2024-10-29
     */
    public function delete_contract($params=[]){
        $id           = $params['id']??'';
        if(!$id) return  $this->jsonMessage(201,false,'ID不能为空!',null);
        Db::name('product_contract')->where(['id'=>$id])->delete();
        return     $this->jsonMessage(200,true,'操作成功','');
    }

    /**
     * @desc   import
     * @author zhagnheng
     * @date   2024-12-16
     */
    public function import($url,$admin_id)
    {
        $data             = Excel::getExcelData('.' . '/' . $url);
        $excelData        = isset($data[0]) ? $data[0] : $data;
        $excelData        = array_values($excelData);
        if(!$excelData)    return json(DefaultResponse(201, false, '暂无数据!', null));
        $number = $excelData[0]['J'] ?? '';
        if(!$number) return json(DefaultResponse(201, false, '找不到批次号!', null));
        $product_contract = Db::name('product_contract')->where(['batch_id'=>$number])->find();
        if($product_contract){
            Db::name('product_contract')->where(['batch_id'=>$number])->update([
                'contact_url'=>$url,
            ]);
            return json(DefaultResponse(200, false, '导入文件成功!', null));
        }else{
            $create_operator = Db::name('system_admin')->where(['id'=>$admin_id])->value('username');
            $insert = [
                'batch_id'       =>$number,
                'contact_url'    =>$url,
                'create_time'    =>date("Y-m-d H:i:s",time()),
                'create_operator'=>$create_operator ?? '未知',
            ];
            Db::name('product_contract')->where(['batch_id'=>$number])->insert($insert);
            return json(DefaultResponse(200, false, '新增批次成功!', null));
        }
        
    }



    /**
     * @desc   确认下单操作消费方法
     * @author zhangheng
     * @date   2025-06-18
     */
    public function confirm_order_consumer($info){
       $batch_id         = $info['batch_id']??'';
       $seller_sku       = $info['seller_sku']??'';
       $single_price     = $info['single_price']??'';
       $suggest_sku_nums = $info['suggest_sku_nums']??'';
       //数据入库;
        try{
            Db::startTrans();
            //更新合同建议流水表;
            Db::name('purchase_suggest_water')->where(['batch_id'=>$batch_id,'seller_sku'=>$seller_sku])->update(
                [
                    'suggest_sku_nums'=>$suggest_sku_nums,
                    'single_price'    =>$single_price,
                ]
            );

           /* //更新产品库存表的在途库存累加;
            Db::name('product_inventory')->where(['seller_sku'=>$seller_sku])
                ->inc('on_way_quantity',$suggest_sku_nums)
                ->update();*/
            Db::commit(); // 提交事务
            return  true;
        }catch (Exception $e){
            Db::rollback(); // 回滚事务
            return  true;
        }
        return  true;
    }


    /**
     * @desc   获取批次号列表
     * @author luckyXiong
     * @date   2024-10-28
     */
    private function get_batch_id($admin_id=''){
        $currentMonth = date('m');
        $currentYear  = date('Y');
        $currentday   = date('d');
        if(strlen($admin_id) > 2){
            $admin_id = substr($admin_id, 0, 2);
        }
        return $currentYear.$currentMonth.$currentday.$admin_id.random_int(100, 999);
    }

    /**
     * @desc   在途数据导出
     * @author zhangheng
     * @date   2025-06-18
     */
    public function expor_onway_sku($params=[]){
        $batch_id = $params['batch_id']??'';
        $field = 'seller_sku,suggest_sku_nums,color,cup,size';
        $list  = Db::name('purchase_suggest_water')
               ->field($field)->where(['batch_id'=>$batch_id])
               ->select()->toArray();
        $header = [];
        $header[] = ['SKU', 'seller_sku'];
        $header[] = ['数量', 'suggest_sku_nums'];
        $tableName = "expor_onway_sku";
        $fileName = "export_" . $tableName . "_" . time();
        return Excel::exportData($list, $header, $fileName, 'xlsx');

    }


}